//
//  ProcessedOrderViewController.m
//  BaishidaiShop
//
//  Created by mac book on 2019/1/18.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "ProcessedOrderViewController.h"
#import "ProcessedSelectedViewController.h"


#import "NewOrderTableViewCell.h"
#import "FinishedOrderFooterView.h"
#import "FinishedOrderHeaderView.h"
#import "HandleOrderHeaderView.h"


#define  GoodsCell_H  60


@interface ProcessedOrderViewController ()<HandleOrderHeaderDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITableViewDelegate,UITableViewDataSource,HandleFooterCallDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong)UIImageView *rightImageView;

@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* finishedHeaderIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;

@property(nonatomic,strong) NSString* telStr;

@end

@implementation ProcessedOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"佰食袋商户";
    self.cellIdentifier = @"OrderCell";
    self.finishedHeaderIdentifier = @"FinishedOrderHeader";
    self.headerIdentifier = @"HandleOrderHeader";
    self.footerIdentitifer = @"FinishedOrderFooter";
    
    
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_right_shaixuan"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButton)];
    
    
   [self setUpSubViews];
}

-(void)rightButton
{
    ProcessedSelectedViewController* controller = [[ProcessedSelectedViewController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self refreshDataSource];

}


-(void)setUpSubViews{
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    [self.tableView registerClass:[NewOrderTableViewCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[HandleOrderHeaderView class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[FinishedOrderHeaderView class] forHeaderFooterViewReuseIdentifier:self.finishedHeaderIdentifier];
    [self.tableView registerClass:[FinishedOrderFooterView class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.rightImageView];

    
}



#pragma mark - Data source
-(void)getData{
    
    NSDictionary* arg = @{
                          @"ince":@"get_order_list",
                          @"sid":[UserHandle shareInstance].userId,
                          @"page":[WMHelper integerConvertToString:self.page.pageIndex]
                          };
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);

        if(self.page.pageIndex == 1){
            [self.page.arrayData removeAllObjects];
        }
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            self.page.recordCount = [[data objectForKey:@"total"] integerValue];
            self.page.pageSize = [[data objectForKey:@"number"]integerValue];
            NSInteger empty = self.page.recordCount % self.page.pageSize;
            if(empty == 0){
                self.page.pageCount = self.page.recordCount/self.page.pageSize;
            }else{
                self.page.pageCount = self.page.recordCount/self.page.pageSize+1;
            }
            
            NSMutableArray *tempArr = [OrderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"data"]];
            [ self.page.arrayData addObjectsFromArray:tempArr];
            
            self.telStr = [NSString stringWithFormat:@"%@",[data objectForKey:@"kf_tel"]];

        }else{
            [self alertHUD:[data objectForKey:@"msg"]];
        }
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf getData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf getData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - UITableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.page.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    OrderModel* orderModel = self.page.arrayData[section];
    if(orderModel.isExpansion){
        return 1;
    }else{
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    OrderModel* orderModel = self.page.arrayData[indexPath.section];
    cell.arrayGoods = orderModel.items;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderModel* orderModel =self.page.arrayData[indexPath.section];
    if(orderModel.isExpansion){
        return   orderModel.items.count*GoodsCell_H;
    }else{
        return 0;
    }
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    OrderModel* orderModel =self.page.arrayData[section];
    if(orderModel.isExpansion){
        
        return 180.f;
    }else{
 
        return 100.f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    OrderModel* orderModel =self.page.arrayData[section];
    NSArray *deliveryArr = orderModel.delivery;
    
    if(orderModel.isExpansion){
        
        if (deliveryArr.count == 0) {
            return 250.f;
        }else{
            return 290.f;
        }
        
    }else{
        return 0.1;
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    OrderModel* orderModel =self.page.arrayData[section];
    if(!orderModel.isExpansion){
        FinishedOrderHeaderView * header = [[FinishedOrderHeaderView alloc] init];
        [header loadData:orderModel index:section+1];
        header.delegate = self;
        header.CalPhoneBlock = ^{
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",orderModel.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        header.SummonKnightBlock = ^{
            
            if ([orderModel.status integerValue] == OrderStatusAlredayJieDan) {//召唤骑士
                [self summonKnightWithOrderModel:orderModel];

            }else if ([orderModel.status integerValue] == OrderStatusWaitInvite){//完成自取
                [self inviteWithOrderModel:orderModel];
                
            }else{//联系骑手
                OrderModel *deliveryModel = orderModel.delivery.firstObject;
                NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",deliveryModel.phone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }
            
            
        };
        return header;
    }else{
        HandleOrderHeaderView * header = [[HandleOrderHeaderView alloc] init];
        [header loadData:orderModel index:section+1];
        header.delegate = self;
        header.CalPhoneBlock = ^{
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",orderModel.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        
        header.SummonKnightBlock = ^{
            
            if ([orderModel.status integerValue] == OrderStatusAlredayJieDan) {//召唤骑士
                [self summonKnightWithOrderModel:orderModel];
                
            }else if ([orderModel.status integerValue] == OrderStatusWaitInvite){//完成自取
                
                [self inviteWithOrderModel:orderModel];
            }else{//联系骑手
                OrderModel *deliveryModel = orderModel.delivery.firstObject;
                NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",deliveryModel.phone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
            }
        };
        return header;
    }
}


-(void)inviteWithOrderModel:(OrderModel *)orderModel{
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"change_order_status",
                          @"sid":[UserHandle shareInstance].userId,
                          @"order_sn":orderModel.order_id
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        
        NSInteger flag = [[data objectForKey:@"ret"] integerValue];
        if(flag == 200){
            
            [self hidHUD:[data objectForKey:@"msg"]];
            [self refreshDataSource];

        }else{
            
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
        NSLog(@"%@",error);
    }];
}

//召唤骑士
-(void)summonKnightWithOrderModel:(OrderModel *)orderModel{
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"Summon_the_knight",
                          @"sid":[UserHandle shareInstance].userId,
                          @"order_id":orderModel.order_id
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        
        NSInteger flag = [[data objectForKey:@"ret"] integerValue];
        if(flag == 200){
            
            NSString *status = [NSString stringWithFormat:@"%@",data[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [self hidHUD:[data objectForKey:@"msg"]];
                [self refreshDataSource];
            }else{
                [self hidHUD:[data objectForKey:@"msg"]];
            }
        }else{
            
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
        NSLog(@"%@",error);
    }];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    OrderModel* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        FinishedOrderFooterView* footer = [[FinishedOrderFooterView alloc] init];
        footer.delegate = self;
        footer.orderModel = self.page.arrayData[section];
        return footer;
    }else{
        return [[UIView alloc]init];
    }
    
}

#pragma mark - OrderHeaderDelegate
-(void)handleOrderHeader:(OrderModel *)entity{
    entity.isExpansion = !entity.isExpansion;
    [self.tableView reloadData];
}
#pragma mark  HandleFooterCallDelegate
-(void)handleFooterCall:(NSString*)phoneNum{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNum];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}




#pragma mark - DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无已处理订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}


#pragma mark - property package
-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
    }
    return _page;
}
/**
 *  悬浮图片
 *
 *
 */
- (UIImageView *)rightImageView
{
    
    CGFloat tabH = TABBAR_HEIGHT;
    CGFloat btnCar_wh = 50;
    CGFloat btnCar_y = SCREEN_HEIGHT-tabH -btnCar_wh -  20 - SafeAreaTopHeight;
    
    
    if (!_rightImageView) {
        _rightImageView = [[UIImageView alloc] init];
        _rightImageView.frame = CGRectMake(SCREEN_WIDTH-btnCar_wh - 10,btnCar_y , btnCar_wh, btnCar_wh);
        _rightImageView.layer.cornerRadius = btnCar_wh/2;
        _rightImageView.image = [UIImage imageNamed:@"icon_bottom_kefu"];
        _rightImageView.contentMode = UIViewContentModeScaleAspectFit;
        _rightImageView.layer.masksToBounds = YES;
        _rightImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageClick)];
        [_rightImageView addGestureRecognizer:tap];
        
        
    }
    return _rightImageView;
}

-(void)tapImageClick{
    
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",self.telStr];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
